#!/bin/bash
#!/usr/bin/env bash
usage() {
    pname=$(basename $0)
    echo "$pname --run_user <run user> --run_group <run user group> --weblogic_home <weblogic home> --domain_path <domain home> --domain_file <file path>"
    exit -1
}

parseOpts() {
    OPT_SPEC=":h-:"
    while getopts "$OPT_SPEC" optchar; do
        case "${optchar}" in
        -)
            case "${OPTARG}" in
            domain_path)
                domain_path="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            weblogic_home)
                weblogic_home="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            domain_file)
                domain_file="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            dat_file)
                dat_file="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;               
            run_user)
                run_user="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            run_group)
                run_group="${!OPTIND}"
                OPTIND=$(($OPTIND + 1))
                ;;
            *)
                if [ "$OPTERR" = 1 ] && [ "${OPT_SPEC:0:1}" != ":" ]; then
                    echo "Unknown option --${OPTARG}" >&2
                fi
                ;;
            esac
            ;;
        h)
            usage
            exit 2
            ;;
        *)
            if [ "$OPTERR" != 1 ] || [ "${OPT_SPEC:0:1}" = ":" ]; then
                echo "Non-option argument: '-${OPTARG}'" >&2
            fi
            ;;
        esac
    done
}

parseOpts "$@"

if [[  ! -n "$weblogic_home" ]] ; then
    echo "ERROR:: Must defined weblogic_home."
    usage
fi

if [[  ! -n "$domain_path" ]] ; then
    echo "ERROR:: Must defined domain_path."
    usage
fi

if [[  ! -n "$domain_file" ]] ; then
    echo "ERROR:: Must defined domain_file."
    usage
fi 

if [[ -d "$dat_file" ]] ; then 
    echo "ERROR:: $dat_file dir not found."
    exit 1
fi

if [[ -d "$run_user" ]] ; then 
    echo "ERROR:: $run_user dir not found."
    exit 1
fi

if [[ -d "$run_group" ]] ; then 
    echo "ERROR:: $run_group dir not found."
    exit 1
fi
wlsserver_bin="$weblogic_home/wlserver/common/bin/"

sh $wlsserver_bin/unpack.sh -domain=$domain_path -template=$domain_file
if [ $? != 0 ]
then
    echo "ERROR:: Weblogic uppack domain failed.$@"
    exit 1
else
    echo "INFO:: Weblogic uppack domain succeed."
fi

#清理备机产生的SerializedSystemIni.dat
rm -f $domain_path/security/SerializedSystemIni.dat
#同步adminserver机器的SerializedSystemIni.dat
cp $dat_file $domain_path/security/SerializedSystemIni.dat

chown -R $run_user:$run_group $weblogic_home

